<template>
	<view class="container">
		<view class="example">
			<uv-form ref="formRef" labelPosition="left" :model="user" :rules="rules" labelWidth="auto">
				<uv-form-item label="用户昵称" prop="nickName" borderBottom required>
					<uv-input v-model="user.nickName" border="none" placeholder="请输入昵称"></uv-input>
				</uv-form-item>
				<uv-form-item label="手机号码" prop="phone" borderBottom required>
					<uv-input v-model="user.phone" border="none" placeholder="请输入手机号码"></uv-input>
				</uv-form-item>
				<uv-form-item label="性别" prop="gender" borderBottom>
					<uv-radio-group v-model="user.gender">
						<uv-radio :customStyle="{margin: '8px'}" v-for="(item, index) in genders" :key="index"
							:label="item.text" :name="item.value">
						</uv-radio>
					</uv-radio-group>
				</uv-form-item>
				<uv-button type="primary" text="提交" customStyle="margin-top: 10px" @click="submit()"></uv-button>
			</uv-form>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { onLoad, onReady } from '@dcloudio/uni-app';
	import { reactive, ref } from "vue";
	import { getUserInfo } from "@/api/login";
	import { editUserInfo } from "@/api/system/user";
	import { useUserStore } from "@/store";

	// 用户store
	const userStore = useUserStore();

	const user = reactive({
		nickName: "",
		phone: "",
		gender: ""
	});

	const genders = reactive([{
		text: '男',
		value: "M"
	}, {
		text: '女',
		value: "F"
	}]);

	const formRef = ref();
	const rules = {
		nickName: {
			type: 'string',
			required: true,
			message: '用户昵称不能为空',
			trigger: ['blur', 'change']
		},
		phone: [{
			type: 'string',
			required: true,
			message: '手机号不能为空',
			trigger: ['blur', 'change']
		}, {
			type: 'string',
			pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
			message: '请输入正确的手机号码',
			trigger: ['blur']
		}]
	}

	// 获取用户信息
	const getUser = async () => {
		const { code, data } = await getUserInfo();
		if (code === 200) {
			user.nickName = data.nickName;
			user.gender = data.gender;
			user.phone = data.phone;
		}
	}

	// 提交
	const submit = () => {
		formRef.value.validate().then(async (res: any) => {
			const param:any = {
				nickName: user.nickName,
				gender: user.gender,
				phone: user.phone
			}
		    await editUserInfo(param);
			await userStore.info();
			// @ts-ignore
			uni.$uv.route({
				type: 'back'
			})
		});
	}

	onLoad(() => {
		getUser()
	});

	onReady(() => {
		formRef.value.setRules(rules);
	});
</script>

<style lang="scss">
	page {
		background-color: #ffffff;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}
</style>
